package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.BaiduConstant;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.properties.BaiduProperties;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.BaiduUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Autowired
    private BaiduUtil baiduUtil;
    @Autowired
    private BaiduProperties baiduProperties;


    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        distanceJudgment(addressBook);//判断配送距离是否在合理范围内

        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.getList(user.getId());
        if (shoppingCartList == null || shoppingCartList.size() == 0)
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        if (addressBook == null) throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        //准备订单表
        Orders order = new Orders();
        BeanUtils.copyProperties(dto, order);
        order.setNumber(System.currentTimeMillis() + "");
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setUserName(user.getName());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDistrictName() + addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        //提交订单表
        ordersMapper.insert(order);
        log.info("新增订单id：{}", order.getId());

        //准备订单详情表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        for (ShoppingCart sc : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(sc, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);
        }
        //提交订单表
        ordersDetailMapper.insert(orderDetailList);

        //清空购物车
        shoppingCartMapper.deleteAll(userId);

        //组装OrderSubmitVO返回
        return OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime()).build();
    }

    private void distanceJudgment(AddressBook addressBook) {
        // 创建 DecimalFormat 对象，并设置保留小数点后六位
        DecimalFormat df = new DecimalFormat("#.000000");
        try {
            //判断距离是否超过5公里
            //发送地理编码请求，获取商家经纬度
            Map shopParams = new LinkedHashMap<String, String>();
            shopParams.put("address", baiduProperties.getShopAddress());
            JSONObject shopJSONObject = baiduUtil.doGet(BaiduConstant.GEOCODING_URL, shopParams);
            double lng = shopJSONObject.getJSONObject("result").getJSONObject("location").getDoubleValue("lng");
            double lat = shopJSONObject.getJSONObject("result").getJSONObject("location").getDoubleValue("lat");
            String shopLng = df.format(lng);
            String shopLat = df.format(lat);
            //发送地理编码请求，获取客户送餐目的地经纬度
            String clientAddress = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
            Map clientParams = new LinkedHashMap<String, String>();
            clientParams.put("address", clientAddress);
            JSONObject clientJSONObject = baiduUtil.doGet(BaiduConstant.GEOCODING_URL, clientParams);
            lng = clientJSONObject.getJSONObject("result").getJSONObject("location").getDoubleValue("lng");
            lat = clientJSONObject.getJSONObject("result").getJSONObject("location").getDoubleValue("lat");
            String clientLng = df.format(lng);
            String clientLat = df.format(lat);
            //发送路线规划请求，获取路线规划距离米数
            Map params = new LinkedHashMap<String, String>();
            params.put("origin", shopLat + "," + shopLng);
            params.put("destination", clientLat + "," + clientLng);
            JSONObject distanceJSONObject = baiduUtil.doGet(BaiduConstant.DIRECTION_URL, params);
            int status = distanceJSONObject.getIntValue("status");
            if (status == 2002) throw new AddressBookBusinessException("下单失败，距离超出限制，无可用骑行路线");
            int distance = distanceJSONObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0).getIntValue("distance");
            log.info("商家与目的地距离：{}", distance + "米");
            //长度换算超过5公里，抛出超远异常
            if (distance > baiduProperties.getDistance())
                throw new AddressBookBusinessException("下单失败，配送距离超出范围（5公里内）");
        } catch (Exception e) {
            log.info("查询地址距离出现异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号：" + ordersDB.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    @Override
    public void reminder(Long id) {
        Orders order = ordersMapper.getById(id);
        if (order == null) throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content", "订单号：" + order.getNumber());
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    /**
     * 接单、拒单、取消订单、派送订单、完成订单共用
     *
     * @param
     * @return
     */
    @Override
    public void updateStatus(Orders order) {
        if (order.getStatus() == Orders.CANCELLED) {
            //微信退款
            //Orders resultOrder = ordersMapper.getById(order.getId());
            //String number = resultOrder.getNumber();
            //BigDecimal amount = resultOrder.getAmount();
            //weChatPayUtil.refund(number, number, amount, amount);
        }
        ordersMapper.update(order);
    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<OrderVO> page = ordersMapper.getPage(dto);
        List<OrderVO> list = page.getResult();
        for (OrderVO vo : list) {
            List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(vo.getId());
            String orderDishes = "";
            for (OrderDetail od : orderDetailList) {
                orderDishes += od.getName() + " × " + od.getNumber() + "; ";
            }
            vo.setOrderDishes(orderDishes);
        }

        PageResult pageResult = new PageResult();
        pageResult.setTotal(page.getTotal());
        pageResult.setRecords(list);
        return pageResult;
    }

    @Override
    public OrderStatisticsVO statistics() {
        return ordersMapper.statistics();
    }

    @Override
    public OrderVO getDetailsByOrderId(Long id) {
        OrderVO vo = ordersMapper.getById(id);
        List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(vo.getId());
        vo.setOrderDetailList(orderDetailList);
        return vo;
    }

    @Override
    public PageResult historyOrders(int page, int pageSize) {
        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        dto.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(page, pageSize);
        Page<OrderVO> pageList = ordersMapper.getPage(dto);
        for (OrderVO vo : pageList) {
            vo.setOrderDetailList(ordersDetailMapper.getByOrderId(vo.getId()));
        }
        return new PageResult(pageList.getTotal(), pageList);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        OrderVO vo = ordersMapper.getById(id);
        vo.setOrderDetailList(ordersDetailMapper.getByOrderId(id));
        return vo;
    }

    @Override
    public void repetition(Long id) {
        Long userId = BaseContext.getCurrentId();
        LocalDateTime nowTime = LocalDateTime.now();
        List<OrderDetail> orderDetailList = ordersDetailMapper.getByOrderId(id);
        for (OrderDetail detail : orderDetailList) {
            ShoppingCart sc = new ShoppingCart();
            BeanUtils.copyProperties(detail, sc, "id");
            sc.setUserId(userId);
            sc.setCreateTime(nowTime);
            shoppingCartMapper.insert(sc);
        }
    }
}
